package com.safety.hat.task;

import com.safety.hat.data.hat.HatHeartInfoBO;
import com.safety.hat.service.hat.adapter.IHatSocketLocationAdapterService;
import com.safety.hat.service.hat.adapter.IHatSocketUserAdapterService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author: lijun
 * @date: 2020/5/25 下午3:58
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class HatOnlineCheckTask {

    private final IHatSocketUserAdapterService hatSocketUserAdapterService;
    private final IHatSocketLocationAdapterService hatSocketLocationAdapterService;

    @Scheduled(cron = "*/30 * * * * ?")
    public void hatOnlineCheck() {
        //log.info("心跳校验-开始");
        //获取所有心跳信息
        ConcurrentHashMap<String, List<HatHeartInfoBO>> allHeartInfo = hatSocketLocationAdapterService.getAllInfo();
        ConcurrentHashMap<String, Session> allOnLineHatUser = hatSocketUserAdapterService.getAllOnLineHatUser();
        //1. 筛选出所有未上报的
        List<String> noSupportInfoList = allOnLineHatUser.keySet().stream()
                .filter(key -> !allHeartInfo.containsKey(key))
                .collect(Collectors.toList());
        noSupportInfoList.forEach(key -> {
            Session session = allOnLineHatUser.get(key);
            try {
                session.close();
                hatSocketUserAdapterService.removeInfo(session);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        //2. 筛选出所有上报超时的
        final long now = System.currentTimeMillis();
        List<String> supportTimeOutList = allHeartInfo.entrySet().stream()
                .filter(entry -> {
                    List<HatHeartInfoBO> hatHeartInfoBOList = entry.getValue();
                    if (CollectionUtils.isEmpty(hatHeartInfoBOList)) {
                        return true;
                    }
                    HatHeartInfoBO lastHeartInfo = hatHeartInfoBOList.get(hatHeartInfoBOList.size() - 1);
                    return now - lastHeartInfo.getReportTime().getTime() > 10 * 1000;
                })
                .map(entry -> entry.getKey())
                .collect(Collectors.toList());
        //2.1 删除所有超时设备
        supportTimeOutList.forEach(deviceId -> {
            hatSocketUserAdapterService.removeInfo(deviceId);
            hatSocketLocationAdapterService.removeInfo(deviceId);
        });
        //log.info("心跳校验-完成");
    }
}       
